package cn.com.demo.shiro.controller;

import cn.com.demo.shiro.entity.TShiroUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.security.auth.login.AccountNotFoundException;

@RestController
@RequestMapping("/auth")
public class LoginController {
    @GetMapping("/login")
    public String login(){
        return "请登录";
    }
    @RequestMapping("/sublogin")
    public String subLogin(String userName,String password) {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(userName,password);
        try {
            subject.login(token);
            subject = SecurityUtils.getSubject();
            // 设置shiro session （非必须）
            Session shiroSession = subject.getSession();
            shiroSession.setAttribute("user",subject.getPrincipal());
            return "OK:"+userName;
        }catch (UnknownAccountException e) {
            return "用户不存在";
        } catch (IncorrectCredentialsException e){
            return "密码不正确";
        }catch (AuthenticationException e) {
           return "登录失败";
        }
    }
    @RequestMapping("/forbidden")
    public String forbidden() {
        return "forbidden:权限不足";
    }
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        TShiroUser user  = (TShiroUser) subject.getPrincipal();
        subject.logout();
        return user.getUsername()+":logout";
    }
}
